package com.app.hmst.main;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.hmst.model.HomestayInfoVO;
import com.app.hmst.model.HouseInfoVO;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

@SuppressLint({ "NewApi", "ValidFragment" })
public class MenuFragment extends Fragment {
	private View v;
	private ImageView logo_icon,arrow_icon,arrow_icon2,menu_icon;
	private RelativeLayout firstMenu,sublevelone,clicktoShowInnerList,layoutInnerList,logoutLayout,viewEvaluate,add_new_homestay,addDetailAssessor;
	private TextView textViewHomeStayName;
	private ListView innerListView;
	private SlidingMenu _sm;
	private boolean isLogin;
	private HomestayInfoVO _infoVo;
	private boolean isShowSubLevelOne = false;
	private boolean isShowSubLevelTwo = false;
	public MenuFragment(SlidingMenu sm,boolean islogin) {
		this._sm = sm;
		this.isLogin = islogin;
	}
	public MenuFragment(SlidingMenu sm,boolean islogin,HomestayInfoVO infoVo){
		this._sm = sm;
		this.isLogin = islogin;
		this._infoVo = infoVo;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		System.gc();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		v = inflater.inflate(R.layout.fragment_menu_main_page, container, false);

		addDetailAssessor = (RelativeLayout) v.findViewById(R.id.RelativeLayout01);
		arrow_icon = (ImageView) v.findViewById(R.id.imageView2);
		arrow_icon2 = (ImageView) v.findViewById(R.id.imageViewJJ);
		sublevelone = (RelativeLayout) v.findViewById(R.id.sublevelone);
		firstMenu = (RelativeLayout) v.findViewById(R.id.each_first_menu_list);
		firstMenu.setVisibility(View.GONE);
		//firstMenu.setOnClickListener(new ClickListToShowSubList1Listener(0, arrow_icon,sublevelone));
		sublevelone.setVisibility(View.GONE);
		clicktoShowInnerList = (RelativeLayout) v.findViewById(R.id.each_level_two_menu_list00);
		layoutInnerList = (RelativeLayout) v.findViewById(R.id.layoutInnerList);
		layoutInnerList.setVisibility(View.GONE);
		logo_icon = (ImageView) v.findViewById(R.id.imageView1);
		textViewHomeStayName = (TextView) v.findViewById(R.id.textViewHomeStayName);
		logoutLayout = (RelativeLayout) v.findViewById(R.id.each_second_menu_list);
		viewEvaluate = (RelativeLayout) v.findViewById(R.id.all_evaluate_layout);
		logoutLayout.setVisibility(View.GONE);
		innerListView = (ListView) v.findViewById(R.id.innerListView);
		add_new_homestay = (RelativeLayout) v.findViewById(R.id.add_new_homestay);
		menu_icon = (ImageView) v.findViewById(R.id.menuIcon);
		add_new_homestay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switchFragment(new GeneralInfoForNewHomeFragment(_sm,_infoVo,null));
			}
		});
		textViewHomeStayName.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switchFragment(new EvaluateFormFragment(_sm,_infoVo,true));
			}
		});
		addDetailAssessor.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switchFragment(new GeneralInfoForAssessor(_sm,_infoVo));
			}
		});
		
		logoutLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
	            builder1.setMessage(getString(R.string.logout_message));
	            builder1.setCancelable(true);
	            builder1.setPositiveButton(getString(R.string.homestay_sync_ok),new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int id) {
	                    dialog.cancel();
	                    SharedPreferences.Editor editor = getActivity().getSharedPreferences("MyPref", 0).edit();
	                    editor.putBoolean("isLogin", false);
	                    editor.commit();
	                    switchFragment(new HomePageFragment(_sm));
	                    
	    				getFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuFragment(_sm,false)).commit();
	                }
	            });
	            builder1.setNegativeButton(getString(R.string.cancel_message),new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int id) {
	                    dialog.cancel();
	                }
	            });
	            AlertDialog alert11 = builder1.create();
	            alert11.show();	          
			}
		});
		viewEvaluate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switchFragment(new ViewAllEvaluatePageFragment(_sm));
			}
		});
		if(_infoVo!=null){
			textViewHomeStayName.setText(_infoVo.name);
			firstMenu.setVisibility(View.VISIBLE);
			
			firstMenu.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(isShowSubLevelOne){
						sublevelone.setVisibility(View.VISIBLE);
						arrow_icon.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
						isShowSubLevelOne =false;
					}else{
						sublevelone.setVisibility(View.GONE);
						arrow_icon.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left));
						isShowSubLevelOne =true;
					}
				}
			});
			arrow_icon2.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(isShowSubLevelTwo){
						innerListView.setVisibility(View.VISIBLE);
						arrow_icon2.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
						isShowSubLevelTwo =false;
					}else{
						innerListView.setVisibility(View.GONE);
						arrow_icon2.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left));
						isShowSubLevelTwo =true;
					}
				}
			});
			logoutLayout.setVisibility(View.VISIBLE);
			if("C".equals(_infoVo.status)){
				menu_icon.setBackground(getResources().getDrawable(R.drawable.marker_icon_selected));
			}else{
				menu_icon.setBackground(getResources().getDrawable(R.drawable.marker_icon));
			}
		}
		
		logo_icon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(_infoVo!=null){
					switchFragment(new GeneralInfoFragment(_sm, _infoVo));
				}else{
					switchFragment(new HomePageFragment(_sm));
				}
				
			}
		});
		if(isLogin){
			arrow_icon.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
			sublevelone.setVisibility(View.VISIBLE);
			arrow_icon2.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
			layoutInnerList.setVisibility(View.VISIBLE);
			//new InitAndLoadSubListLevel2(innerListView,_infoVo).execute();
			SubMenuLevel2Adapter subLevel1 = new SubMenuLevel2Adapter(getActivity(), _infoVo.houses(),_sm,innerListView,_infoVo);
			innerListView.setAdapter(subLevel1);
		}

		return v;
	}
	
	public int getTotalHeightofListView(ListView listView) {

	    ListAdapter mAdapter = listView.getAdapter();

	    int totalHeight = 0;

	    for (int i = 0; i < mAdapter.getCount(); i++) {
	        View mView = mAdapter.getView(i, null, listView);

	        mView.measure(
	                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),

	                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

	        totalHeight += mView.getMeasuredHeight();
	        Log.w("HEIGHT" + i, String.valueOf(totalHeight));

	    }
	    return totalHeight;
//	    ViewGroup.LayoutParams params = listView.getLayoutParams();
//	    params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
//	    listView.setLayoutParams(params);
//	    listView.requestLayout();

	}
	
//	public class ClickTOshowInner implements OnClickListener{
//		private int ste;
//		public ClickTOshowInner(int ste){
//			this.ste = ste;
//		}
//		@Override
//		public void onClick(View v) {
//			// TODO Auto-generated method stub
//			if(ste==0){
//				arrow_icon2.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
//				layoutInnerList.setVisibility(View.VISIBLE);
//				new InitAndLoadSubListLevel2(innerListView,_infoVo).execute();
//				ste=1;
//			}else{
//				layoutInnerList.setVisibility(View.GONE);
//				arrow_icon2.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left));
//				ste=0;
//			}
//		}
//		
//	}
	private void switchFragment(Fragment fragment) {
		if (getActivity() == null)
			return;

		if (getActivity() instanceof HomeStayMainActivity) {
			HomeStayMainActivity fca = (HomeStayMainActivity) getActivity();
			fca.switchContent(fragment);
		}
	}

	public class ClickTOshowInner implements OnClickListener{

		private RelativeLayout _subLevelone;
		public ClickTOshowInner(RelativeLayout sublevelone){	
			this._subLevelone = sublevelone;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switchFragment(new EvaluateFormFragment(_sm,_infoVo,true));
		}
		
	}
	public class InitAndLoadSubListLevel2 extends AsyncTask<String, Void, List<HouseInfoVO>> implements OnCancelListener{
		ProgressHUD mProgressHUD;
		private ListView _viewList;
		private HomestayInfoVO _infoo;
		public InitAndLoadSubListLevel2(ListView listView,HomestayInfoVO info){
			this._viewList = listView;
			this._infoo = info;
		}
		
    	@Override
    	protected void onPreExecute() {
        	mProgressHUD = ProgressHUD.show(getActivity(),"Loading Content...", true,true,this);
    		super.onPreExecute();
    	}
		@Override
		protected List<HouseInfoVO> doInBackground(String... params) {
			// TODO Auto-generated method stub
			
			return _infoo.houses();
		}
		
		@Override
		protected void onPostExecute(List<HouseInfoVO> result) {
			super.onPostExecute(result);
			if (result != null) {
			    _viewList.setDividerHeight(0);
				mProgressHUD.dismiss();
				SubMenuLevel2Adapter subLevel1 = new SubMenuLevel2Adapter(getActivity(), result,_sm,_viewList,_infoo);
				_viewList.setAdapter(subLevel1);
				
			} else {
				mProgressHUD.dismiss();
			}
			
		}
		@Override
		public void onCancel(DialogInterface dialog) {
			// TODO Auto-generated method stub
			mProgressHUD.dismiss();
		}
	}
}
